#include <iostream>
#include "../src/SenderXml.h"
#include "../src/ReceiverXml.h"
#include "utils.h"
#include "ListenerPlug.h"
#include "../src/NetException.h"

using namespace net;
using namespace rapidxml;

void sendBlock(int count) {
	SenderXml sender;
	ExtXml tx_xml;
	ExtXml rx_xml;

	xml_node<>* root = tx_xml.allocate_node(node_element, "root");
	for (int i = 0; i < count; ++i) {
		xml_node<>* node = tx_xml.allocate_node(node_element, "node");
		node->append_attribute(tx_xml.allocate_attribute("attr", "val"));
		root->append_node(node);
	}
	tx_xml.append_node(root);

	try {
		rx_xml = sender.send("127.0.0.1", 1234, tx_xml);
	} catch (net::NetException &e) {
		std::cout << e.what() << std::endl;
	}

	std::cout << "Printing echo message" << std::endl;

	if (tx_xml == rx_xml) {
		std::cout << "count = " << count << " , OK" << std::endl;
	} else {
		std::cout << "count = " << count << " , ERROR" << std::endl;
		exit(1);
	}
}

int main(int argc, char* argv[]) {
	/*
	try {
		throw NetException("TestEx");
	} catch (NetException e) {
		std::cout << e.what() << std::endl;
	}
	return 0;
	*/

	ListenerPlug listener;
	std::cout << "Hello world!" << std::endl;
	SenderXml sender;
	ReceiverXml receiver;
	receiver.subscribe(&listener);

	try {
		receiver.start(1234);

		for (int i = 0; i < 10000; i += 200) {
			sendBlock(i);
		}
	} catch (net::NetException &e) {
		std::cout << e.what() << std::endl;
	}

	//sleep(1);
	char a;
	//std::cin >> a;
	receiver.stop();
}
